package com.mrs.gauss.interfaces.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class execUtil {
    public static int exec(String command, int timeoutInSeconds) {
        try {
            ProcessBuilder pb = new ProcessBuilder(command.split(" "));
            pb.redirectErrorStream(true);
            Process process = pb.start();

            // 读取进程的输出
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待进程执行结束
            if (!process.waitFor(timeoutInSeconds, TimeUnit.SECONDS)) {
                process.destroy();
                return -1; // 超时返回-1
            }

            return process.exitValue(); // 返回进程的退出值
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return -1; // 发生异常返回-1
        }
    }
}
